import React, { useEffect, useState } from "react";
import { Button, Space, Steps, Table } from "antd";
import { useLocation } from "@umijs/max";
import { cabinetTypes, orderTypes } from "@/constants/types";
import { fetchBookingDetail, bookingRemoveOrder, bookingMoveOrder, fetchBookingListOrders } from "../services";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import { calculateTableWidth } from "@/utils/util";
import { PlusOutlined } from "@ant-design/icons";
import type { ColumnsType } from 'antd/es/table';
import CabinetOrderManage from "../modals/CabinetOrderManage";
import { useRequest } from "ahooks";
import dayjs from "dayjs";

const CabinetHeader = ({info}: {info: cabinetTypes}) => {

  return (
    <Space>
      <div style={{marginBottom: 20}}>操作单号: <strong>{info?.orderCode || ''}</strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>柜号/虚拟柜号: <strong>{info?.cabinetCode || ''}</strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>SO: <strong>{info?.so || ''}</strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>业务类型: <strong><XlTableDictColumn value={info?.type} type="cabinetType" /></strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>同行名称: <strong>{info?.peerSupplierName || ''}</strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>状态: <strong>{info?.bookingStatusText || ''}</strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>船司: <strong>{info?.shipName || ''}</strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>航名航次: <strong>{info?.shipLineNo || ''}</strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>业务时间: <strong>{info?.businessTime || ''}</strong></div>
      <div style={{marginBottom: 20, marginLeft: 20}}>装柜标记人: <strong>{info?.cabinetBy || ''}</strong></div>
    </Space>
  );
}

const CabinetTrackPart = ({tracks}: {tracks: any []}) => {
  const current = tracks?.findIndex((v: any) => v.flag === 0);

  return (
    <div style={{marginTop: 30, padding: 20, backgroundColor: '#f5f5f5', borderRadius: '10px'}}>
      <Steps
        current={current - 1}
        items={tracks?.map((v: any) => ({
          title: v?.nodeName,
          description: v?.nodeTime
        }))}
      />
    </div>
  );
}

const CabinetOrders = ({info}: {info: cabinetTypes}) => {
  const [dataSource, setDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<orderTypes | null>(null);
  const {loading: inLoading, runAsync: bookingMoveOrderApi} = useRequest(bookingMoveOrder, {manual: true});
  const {loading: outLoading, runAsync: bookingRemoveOrderApi} = useRequest(bookingRemoveOrder, {manual: true});

  const searchOrders = (id: string) => {
    fetchBookingListOrders({id}).then(
      res => {
        setDataSource(res || []);
      }
    )
  }

  const handleRemove = (record: orderTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }

  const cabinetOrderManageProps = {
    title: currentRow ? '移出备注' : '漏配移入',
    visible,
    currentRow,
    loading: inLoading || outLoading,
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: any) => {
      try {
        const apiFunc = currentRow ? bookingRemoveOrderApi : bookingMoveOrderApi;
        const res = await apiFunc({...params, id: info?.id});
        if (res?.code === '0') {
          cabinetOrderManageProps.onCancel();
          searchOrders(info?.id);
        }
      } catch (err) {
        console.log(err);
      }
    }
  }

  const columns: ColumnsType<orderTypes> = [
    {
      title: "订单号",
      dataIndex: "orderCode",
      fixed: 'left',
      width: 150
    },
    {
      title: "外部单号",
      dataIndex: "exOrderCode",
      width: 150
    },
    {
      title: "下单时间",
      dataIndex: "orderTime",
      width: 180
    },
    {
      title: "下单公司简称",
      dataIndex: "customerName",
      width: 120
    },
    {
      title: "下单手机号",
      dataIndex: "mobile",
      width: 150
    },
    {
      title: "所属销售",
      dataIndex: "salesName",
      width: 120
    },
    {
      title: "产品名称",
      dataIndex: "productName",
      width: 120
    },
    {
      title: "国家",
      dataIndex: "countryName",
      width: 100
    },
    {
      title: "起始地",
      dataIndex: "sportName",
      width: 120
    },
    {
      title: "目的港",
      dataIndex: "dportName",
      width: 120
    },
    {
      title: "目的地",
      dataIndex: "destCode",
      width: 100
    },
    {
      title: "派送方式",
      dataIndex: "deliveryMethod",
      width: 120
    },
    {
      title: "件数",
      dataIndex: "totalPieces",
      width: 100
    },
    {
      title: "体积/CBM",
      dataIndex: "totalVol",
      width: 150
    },
    {
      title: "重量/KG",
      dataIndex: "totalWeight",
      width: 150
    },
    {
      title: "操作",
      dataIndex: "options",
      width: 150,
      fixed: 'right',
      render: (_, record) => <Button type="link" onClick={() => handleRemove(record)}>移出</Button>
    },
  ];

  useEffect(() => {
    if (info?.id) {
      searchOrders(info?.id)
    } else {
      setDataSource([]);
    }
  }, [info?.id])

  return (
    <>
      <div style={{display: 'flex', justifyContent: 'flex-end', marginTop: 30}}>
        <Button type="primary" onClick={() => setVisible(true)}><PlusOutlined />漏配移入</Button>
      </div>
      <Table
        bordered
        style={{marginTop: 10}}
        columns={columns}
        dataSource={dataSource}
        rowKey="id"
        scroll={{x: calculateTableWidth(columns)}}
        pagination={{pageSize: 10}}
      />
      {visible && <CabinetOrderManage {...cabinetOrderManageProps} />}
    </>
  );
}

const CabinetDetail = () => {
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const id = searchParams.get('id');

  const [detail, setDetail] = useState<cabinetTypes>({});

  const fetchDetail = async () => {
    const res = await fetchBookingDetail({id});
    setDetail(res || {});
  }


  useEffect(() => {
    if (id && location.pathname === '/order-manage/cabinet-detail') {
      fetchDetail(id);
    } else {
      setDetail({});
    }
  }, [id])

  return (
    <>
      <CabinetHeader info={detail} />
      <CabinetTrackPart tracks={detail?.tracks || []} />
      <CabinetOrders info={detail} />
    </>
  );
}
export default CabinetDetail;